<?php
/*
$JA#COPYRIGHT$
*/
defined ( '_JEXEC' ) or die ( 'Restricted access' );
jimport ( 'joomla.event.plugin' );
jimport ( 'joomla.user.helper' );

class plgSystemPlg_JAJB_JomSocial extends JPlugin {
	
	var $plugin;
	var $plgParams;
	var $user;
	
	function plgSystemPlg_JAJB_JomSocial(&$subject, $config) {
		parent::__construct ( $subject, $config );
		$this->plugin = &JPluginHelper::getPlugin ( 'system', 'plg_jajb_jomsocial' );
		$this->plgParams = new JParameter ($this->plugin->params);
		
		// Load user
	    $this->user = JFactory::getUser ();
	}
	
	function onAfterInitialise() {
	    global $mainframe, $option;
	    
	    $currentSession = JSession::getInstance('none',array());
        $checked = $currentSession->get("plg_jajb_jomsocial", 0);
        $params = $this->plgParams;
        
        $syncOption = $params->get("update_when", "0");		
		$userType = $params->get("default_user", 'ja_resumes');
		
        $user = $this->user;
        
		if ($mainframe->isAdmin () || $user->id == 0 || $checked)  {
			return;
		}
		
		// Check JAJobBoard and JomSocial installed
		$db =& JFactory::getDBO();
		
		$query = "SELECT id FROM #__ja_profiles LIMIT 1";
		$db->setQuery($query);
		$resultJB = $db->query();
		
		$query = "SELECT userid FROM #__community_users LIMIT 1";
		$db->setQuery($query);
		$resultJS = $db->query();
		
		if( !$resultJB || !$resultJS ){
			$currentSession->set("plg_jajb_jomsocial", 1);
			return ;
		}
	    
		// Check user in JomSocial but not in JAJobBoard
		$query = "SELECT userid, avatar FROM #__community_users 
		          WHERE userid NOT IN (SELECT user_id FROM #__ja_profiles )  
		          AND userid NOT IN (SELECT user_id FROM #__ja_resumes )
		          AND userid IN ( SELECT id FROM #__users WHERE usertype NOT IN ('Administrator', 'Manager', 'Super Administrator', 'Public Back-end') ) 
		          AND userid = ".$user->id." ";
		$db->setQuery($query);
        
		$result = $db->loadObject();
		
		if( !$result ){
			// Disable update profile function
			if( $syncOption != 0 ){
				// Update profile
				// Check user exist in ja_profiles an comunitiy_users
				$query = "SELECT userid, avatar FROM #__community_users 
					  WHERE ( userid IN (SELECT user_id FROM #__ja_profiles ) OR userid IN (SELECT user_id FROM #__ja_resumes ) )
					  AND userid IN ( SELECT id FROM #__users WHERE usertype NOT IN ('Administrator', 'Manager', 'Super Administrator', 'Public Back-end') ) 
					  AND userid = ".$user->id." ";
				$db->setQuery($query);
				$result = $db->loadObject();
				// If user exist in JAJobBoard and JomSocial				
				if( $result ){
					// Get user info in JAJobBoard				
					$existIn = "ja_profiles";
					$query = "SELECT * FROM #__ja_profiles WHERE user_id = ".$user->id." ";
					$db->setQuery($query);
					$jbUser = $db->loadObject();				
					if( ! $jbUser ) {
						$query = "SELECT * FROM #__ja_resumes WHERE user_id = ".$user->id." ";
						$db->setQuery($query);
						$jbUser = $db->loadObject();
						$existIn = "ja_resumes";
					}
					
					// Get user info in JomSocial
					$query = "SELECT id, (SELECT fieldcode FROM #__community_fields WHERE #__community_fields.id = #__community_fields_values.field_id) as field_id, value FROM #__community_fields_values WHERE user_id = ".$user->id." ";
					$db->setQuery($query);
					$jsUser = $db->loadObjectList();
					
					if( $jbUser && $jsUser ){
						if( $existIn == "ja_profiles" )
							$paramUser = $params->get("employer_profile", "");
						else
							$paramUser = $params->get("jobseeker_profile", "");						
						$paramUser = str_replace(array("\t", "\n"), " ", $paramUser);						
						$paramUser = explode(" ", $paramUser);
						
						// Update option
						$updateOption = $params->get("update_option", "1");
						
						if( is_array($paramUser) ){
							foreach ($paramUser as $string){	            
								$string = explode("=", $string);
								if( count($string) == 2 ){	                
									if( $this->checkField_inserted($userType, $string[0]) ){
										foreach($jsUser as $jsData){											
											if( $jsData->field_id == $string[1] ){
												if( isset( $jbUser->$string[0] ) ){													
													// Update from JAJobBoard to JomSocial
													if( $syncOption == 1){
														if( $updateOption == 1 )
															$sql = "UPDATE #__community_fields_values SET `value` = '".mysql_real_escape_string($jbUser->$string[0])."' WHERE (`value` IS NULL OR `value` = '' ) AND id = ".$jsData->id;
														else
															$sql = "UPDATE #__community_fields_values SET `value` = '".mysql_real_escape_string($jbUser->$string[0])."' WHERE id = ".$jsData->id;
													}
													// Update from JomSocial to JAJobBoard
													if( $syncOption == 2){
														if( $updateOption == 1 )
															$sql = "UPDATE #__".$existIn." SET `".$string[0]."` = '".mysql_real_escape_string($jsData->value)."' WHERE ( `".$string[0]."` IS NULL OR `".$string[0]."` = '' ) AND id = ".$jbUser->id;
														else
															$sql = "UPDATE #__".$existIn." SET `".$string[0]."` = '".mysql_real_escape_string($jsData->value)."' WHERE id = ".$jbUser->id;
													}
													$db->setQuery($sql);
													$db->query();													
												}
											}
										}
										// Avatar proccess
										if( $string[1] == "avatar" && isset( $jbUser->$string[0] ) ){
											jimport('joomla.filesystem.file');
																					
											// Update from JAJobBoard to JomSocial
											if( $syncOption == 1){
												$file = $jbUser->$string[0];
												if( file_exists( JPATH_SITE.DS.$file ) ){
													$fileInfo = pathinfo( JPATH_SITE.DS.$file );
													if( @copy( JPATH_SITE.DS.$file, JPATH_SITE.DS."images".DS."avatar".DS.$fileInfo['basename']) ){
														$file = "images/avatar/".$fileInfo['basename'];														
													}
												}
												if( $updateOption == 1 )
													$sql = "UPDATE #__community_users SET `avatar` = '".mysql_real_escape_string($file)."', `thumb` = '".mysql_real_escape_string($file)."'  WHERE ( `avatar` IS NULL OR `avatar` = '' ) AND userid = ".$jbUser->user_id;
												else
													$sql = "UPDATE #__community_users SET `avatar` = '".mysql_real_escape_string($file)."', `thumb` = '".mysql_real_escape_string($file)."' WHERE userid = ".$jbUser->user_id;
											}
											// Update from JomSocial to JAJobBoard
											if( $syncOption == 2){
												$file = $result->avatar;
												$folder = str_replace("ja_", "", $existIn);
												if( file_exists( JPATH_SITE.DS.$result->avatar ) ){
													$fileInfo = pathinfo( JPATH_SITE.DS.$result->avatar );
													if( @copy( JPATH_SITE.DS.$result->avatar, JPATH_SITE.DS."images".DS."stories".DS."jbuploads".DS.$folder.DS.$fileInfo['basename']) ){
														$file = "images/stories/jbuploads/".$folder."/".$fileInfo['basename'];														
													}
												}
												if( $updateOption == 1 )
													$sql = "UPDATE #__".$existIn." SET `".$string[0]."` = '".mysql_real_escape_string($file)."' WHERE ( `".$string[0]."` IS NULL OR `".$string[0]."` = '' ) AND id = ".$jbUser->id;
												else
													$sql = "UPDATE #__".$existIn." SET `".$string[0]."` = '".mysql_real_escape_string($file)."' WHERE id = ".$jbUser->id;
												
											}
											$db->setQuery($sql);
											$db->query();											
										}
									}
								}
							}
						}
					}
				}
			}
			
			$currentSession->set("plg_jajb_jomsocial", 1);
			return ;
		}
		
		if( $userType == "match_value" ){
			$configValueEmp = $params->get("match_value_employer", '');
			$configValueJob = $params->get("match_value_jobseeker", '');
			if( strpos($configValueEmp, "=") !== false  && strpos($configValueJob, "=") !== false ){
				$configValueEmp = explode("=", $configValueEmp);
				$configValueJob = explode("=", $configValueJob);
				
				$query = "SELECT value FROM #__community_fields_values WHERE user_id = ".$user->id.
		                       " AND field_id IN ( SELECT id FROM #__community_fields WHERE fieldcode = '".$configValueEmp[0]."' ) 
		                        AND value = '".$configValueEmp[1]."'";
		    	$db->setQuery($query);
		    	if( $db->loadResult() ){
		    		$userType = "ja_profiles";
		    	}else{
		    		$query = "SELECT value FROM #__community_fields_values WHERE user_id = ".$user->id.
		                       " AND field_id IN ( SELECT id FROM #__community_fields WHERE fieldcode = '".$configValueJob[0]."' ) 
		                        AND value = '".$configValueJob[1]."'";
		    		$db->setQuery($query);
		    		if( $db->loadResult() )
		    			$userType = "ja_resumes";
		    		else{
		    			// JError::raiseWarning(0, JText::_("JA JobBoard - JomSocial plugin can't create user in JA JobBoard be cause wrong config"));
		    			$currentSession->set("plg_jajb_jomsocial", 1);
		    			return ;
		    		}
		    	}
			}
		}
		
		// Insert to JAJobBoard system.
		$data = $this->buildFieldData($userType, $user, $result);
		
		$field = array();
		$value = array();
		foreach ($data as $k=>$v){
		    $field[] = "`{$k}`";
		    $value[] = "'".mysql_real_escape_string($v)."'";
		}
		
		$field = implode(",", $field);
		$value = implode(",", $value);
		
		if( empty($field) )
		  $sql = "INSERT INTO #__{$userType}(user_id,  approved) VALUES ('".$user->id."', '1')";
		else 
		  $sql = "INSERT INTO #__{$userType}(user_id,  approved, {$field}) VALUES ('".$user->id."', '1', {$value})";
		
		$db->setQuery($sql);		
		$db->query();
		
		if( $userType == "ja_resumes" )
		  $user->setParam('usertype', "Job Seeker User");
		else 
		  $user->setParam('usertype', "Employer User");
    	$user->save();
    		
		$currentSession->set("plg_jajb_jomsocial", 1);
	}
	
	function buildFieldData($userType, $user, $jsUser){
	    $params = $this->plgParams;
	    $db =& JFactory::getDBO();	
	    $mapField = array();
	    
	    if( $userType == "ja_resumes" ){
	        $mapField = $this->explodeToArray($params->get("jobseeker_profile", ""), $userType, $jsUser);
	    }else{
	        $mapField = $this->explodeToArray($params->get("employer_profile", ""), $userType, $jsUser);
	    }
	    return $mapField;
	}
	
	function explodeToArray($params, $userType, $jsUser){
	    $db =& JFactory::getDBO();
	    $user = $this->user;
	    
	    $arrReturn = array();
	    if( empty($params) )
	       return $arrReturn;
	    
	    $params = str_replace(array("\n", "\t"), " ", $params);
	    $params = explode(" ", $params);
	    
	    if( is_array($params) ){
	        foreach ($params as $string){	            
	            $string = explode("=", $string);
	            if( count($string) == 2 ){	                
	                if( $this->checkField_inserted($userType, $string[0]) ){	                    
	                    // Get value from JomSocial
	                    $query = "SELECT value FROM #__community_fields_values WHERE user_id = ".$user->id.
	                       " AND field_id IN ( SELECT id FROM #__community_fields WHERE fieldcode = '".$string[1]."' ) ";
	                    $db->setQuery($query);
	                    
	                    $arrReturn[ $string[0] ] = $db->loadResult();
	                    
	                    if( $string[1] == "avatar" ){
	                        $arrReturn[ $string[0] ] = $jsUser->avatar;
	                    }
	                }
	            }
	        }
	        return $arrReturn;
	    }else return $arrReturn;
	}
	
	
    function checkField_inserted($tableName, $columnName)
    {
    	//Global variable, $db for database name, these variable are common in whole application so stored in a global variable, alternatively you can pass this as parameters of function.
    	
    	$jconfig = new JConfig();
    	$databasename = $jconfig->db;
    	
    	//Getting table fields through mysql built in function, passing db name and table name	
    	$tableFields = @mysql_list_fields($databasename, $jconfig->dbprefix.$tableName);
    	if( !$tableFields )
    		return 0;
    	
    	//loop to traverse tableFields result set
    	for($i=0;$i<mysql_num_fields($tableFields);$i++){
    		//Using mysql_field_name function to compare with column name passed. If they are same function returns 1
    		
    		if(mysql_field_name($tableFields, $i)==$columnName)
    		return 1;
    	} //end of loop
    	return 0;
    }
}

?>